<?php

namespace app\common\model\mycurrency;

use addons\epay\Epay;
use think\Config;
use think\Exception;
use think\Model;
use think\Queue;
use traits\model\SoftDelete;
use weixin\Wechatapppay;

use alipay;



class LeaseDeposit extends Model
{

    //use SoftDelete;

    // 表名
    protected $name = 'mycurrency_lease_deposit';

    // 追加属性
    protected $append = [
        'status_text'
    ];

    const STATUS_YIQUXIAO = -1;//状态 = 已取消
    const STATUS_ZHIFUCHAOSHI = -2;//状态 = 支付超时
    const STATUS_WEIZHIFU = 1;//状态 = 未支付
    const STATUS_YIZHIFU = 2;//状态 = 已支付
    const STATUS_TUIKUANGZHONG = 3;//状态 = 已退款
    const STATUS_YITUIKUAN = 4;//状态 = 已退款
    const STATUS_YIKOUKUAN= 5;//状态 = 已扣款

    const PAY_TYPE_WECHAT             = 1;//支付类型 = 微信支付
    const PAY_TYPE_ALIPAY             = 2;//支付类型 = 支付宝支付
    const PAY_TYPE_YUE                = 3;//支付类型 = 余额

    const REFUND_TYPE_YUANLU = 1;//退款方式:原路退回
    const REFUND_TYPE_XIANXIA = 2;//退款方式:线下退款

    /**
     * 押金下单
     * @param int $user_id 用户id
     * @param int $lease_order_id 订单id
     * @param int $advance_fee 需支付金额
     */
    public static function depositAdd($user_id,$lease_order_id = null,$advance_fee = null){
        if(!$advance_fee){
            $advance_fee = LeaseConfig::where(['id' => 1])->value('deposit');
        }
        //添加订单
        $increase = [
            'user_id' => $user_id,
            'amount' => $advance_fee,
            'status' => self::STATUS_WEIZHIFU,
            'deduction_fee' => 0,
            'refund_fee' => 0,
            'place_time' => time(),
            'createtime' => time(),
            'lease_order_id' => $lease_order_id,
        ];
        $deposit = self::create($increase);
        if (!$deposit){
            throw new Exception('押金记录生成失败');
            return false;
        }
        //添加定时任务
        $queue_default = config('queue.default');
        Queue::later(60, "addons\mycurrency\controller\job\Lease@depositPaymentVerification", ['deposit_id' => $deposit['id']], $queue_default);

        return $deposit;
    }


    /**
     * 押金支付成功后逻辑处理
     * @param int $deposit_id 押金支付记录id
     * @param int $pay_type 用户支付方式
     */
    public static function paymentSuccess($deposit_id,$pay_type){
        $deposit = self::where(['id' => $deposit_id,'deletetime' => null])->find();
        if(!$deposit){
            throw new Exception('记录不存在');
            return false;
        }
        if($deposit['status'] == self::STATUS_ZHIFUCHAOSHI){//押金支付超市 - 在用户支付的过程中系统触发了超时
            $deposit->pay_type = $pay_type;
            $deposit->status = self::STATUS_YIZHIFU;
            $deposit->payment_time = time();
            $deposit->save();
            //因为订单已经取消 接着进行退款
            self::depositRefund($deposit_id);
            return;
        }
        if($deposit['status'] != self::STATUS_WEIZHIFU){
            throw new Exception('非待支付状态');
            return false;
        }

        //修改押金支付订单状态
        $deposit->pay_type = $pay_type;
        $deposit->status = self::STATUS_YIZHIFU;
        $deposit->payment_time = time();
        $deposit->save();

        //租赁订单处理
        trace(["26========================处理lease_order_id报错问题_paymentSuccess==============================" => $deposit],'error');
        if($deposit->lease_order_id != null){//押金支付成功，开始开锁
            //修改租赁订单状态

            LeaseOrder::where(['id' => $deposit->lease_order_id])->update([
                'use_status' => LeaseOrder::USE_STATUS_JINXINGZHONG,
            ]);
            //查询隔扣内杆子的卡id
            LeaseOrder::orderBlockIdQuery($deposit->lease_order_id);
        }
    }

    /**
     * 申请退押金
     * @param int $deposit_id 押金记录id
     */
    public static function depositRefund($deposit_id){
        trace('========================开始处理结束订单8-3-34-5-1 开始调用退款接口==============================押金支付记录id：' . $deposit_id);
        $deposit = self::where(['id' => $deposit_id,'deletetime' => null])->find();
        trace('========================开始处理结束订单8-3-34-5-2 押金支付记录信息==============================' . json_encode($deposit));
        if(!$deposit){
            throw new Exception('充值记录不存在');
            return false;
        }
        if($deposit['status'] != self::STATUS_YIZHIFU){
            throw new Exception('非已支付状态');
            return false;
        }
        //修改充值记录状态
        trace('========================开始处理结束订单8-3-34-5-3 开始修改押金支付记录状态==============================' .self::STATUS_TUIKUANGZHONG . '=====' . time());
        $deposit->status = self::STATUS_TUIKUANGZHONG;//状态修改为退款中
        $deposit->refund_time = time();
        $deposit->save();
        trace("========================开始处理结束订单8-3-34-5-4 修改完押金支付记录状态=============================={$deposit->amount}========{$deposit->deduction_fee}");
        $refund_fee = $deposit->amount - $deposit->deduction_fee;//退款金额 = 支付金额 - 扣款金额
        trace("========================开始处理结束订单8-3-34-5-5 退款金额=============================={$refund_fee}");
        if($refund_fee <= 0){//没有需要退款的金额
            $deposit->status = self::STATUS_YIKOUKUAN;//状态修改为已扣款
            $deposit->save();
        }else{
            $deposit->refund_fee = $refund_fee;//退款金额
            $deposit->save();
            trace("========================开始处理结束订单8-3-34-5-6 开始根据支付方式处理退款=============================={$deposit->pay_type}");
            //根据支付方式原路退回押金
            if($deposit->pay_type == self::PAY_TYPE_WECHAT || $deposit->pay_type == self::PAY_TYPE_ALIPAY){//押金支付方式 微信or支付宝 yss临时 未实现
                //if($deposit->pay_type == self::PAY_TYPE_WECHAT ){//微信支付
                //}
                //执行线上退款
                trace('========================开始处理结束订单8-3-34-5-7 开始执行线上退款==============================' . $deposit->id);
                self::wechatRefund($deposit->id);
                trace('========================开始处理结束订单8-3-34-5-8 执行线上退款完成==============================');
            }elseif ($deposit->pay_type == self::PAY_TYPE_YUE){//余额支付
                //退回用户余额
                //UserMoneyLog::moneyChange($deposit['user_id'],$deposit->refund_fee,UserMoneyLog::TYPE_TUIHUIYAJIN,[
                //    'memo' => '租赁陪护床押金退回',
                //    'lease_deposit_id' => $deposit->id,
                //]);
                trace('========================开始处理结束订单8-3-34-5-9 开始执行余额退款==============================' . $deposit['user_id']);
                $distribution_user = OperateDistributionUser::where(['user_id' => $deposit['user_id']])->find();
                trace('========================开始处理结束订单8-3-34-5-10 查询分销用户信息==============================' . json_encode($distribution_user));
                //扣除用户分销余额
                trace("========================开始处理结束订单8-3-34-5-11 开始扣除用户分销余额=============================={$distribution_user->id}======{$deposit->refund_fee}====" . json_encode(['memo' => '押金退回', 'lease_deposit_id' => $deposit->id,]));
                OperateDistributionMoneylog::moneyChange($distribution_user->id,$deposit->refund_fee,OperateDistributionMoneylog::TYPE_YAJINTUIHUEI,[
                    'memo' => '押金退回',
                    'lease_deposit_id' => $deposit->id,
                ]);
                trace('========================开始处理结束订单8-3-34-5-12 扣除用户余额完成==============================');
                //处理押金退款成功后逻辑

                self::refundSuccess($deposit->id,self::REFUND_TYPE_YUANLU);
            }
        }



    }

    /**
     * 押金退款成功后逻辑处理
     * @param int $deposit_id 押金支付记录id
     * @param int $refund_type 退款方式:1=原路退回,2=线下退款【一些支付超过一年的有管理线下退款后更改状态】
     */
    public static function refundSuccess($deposit_id,$refund_type){
        $deposit = self::where(['id' => $deposit_id,'deletetime' => null])->find();
        if(!$deposit){
            throw new Exception('记录不存在');
            return false;
        }
        if($deposit['status'] != self::STATUS_TUIKUANGZHONG){
            throw new Exception('非退款中状态');
            return false;
        }

        //修改订单状态
        $deposit->refund_type = $refund_type;
        $deposit->status = self::STATUS_YITUIKUAN;
        $deposit->refund_complete_time = time();
        $deposit->save();

    }

    /**
     * 押金扣款
     * @param int $deposit_id 押金支付记录id
     * @param int $deduction_fee 扣款金额
     */
    public static function deduction($deposit_id,$deduction_fee){
        trace("========================开始处理结束订单8-3-34-1 开始使用押金支付租赁费用==============================押金支付记录id：{$deposit_id}===========扣款金额：{$deduction_fee}");
        $deposit = self::where(['id' => $deposit_id,'deletetime' => null])->find();
        trace("========================开始处理结束订单8-3-34-2 押金支付记录==============================" . json_encode($deposit));
        if(!$deposit){
            throw new Exception('押金记录不存在');
            return false;
        }
        if($deposit['status'] != self::STATUS_YIZHIFU){
            throw new Exception('押金非已支付状态');
            return false;
        }
        trace("========================开始处理结束订单8-3-34-2 开始处理押金扣款逻辑=============================={$deposit->amount}===={$deduction_fee}====$deposit->amount");
        $deduction_fee = $deduction_fee <= $deposit->amount ? $deduction_fee : $deposit->amount;//处理扣款金额 如果扣款金额 大于押金支付金额 最多只能扣押金支付的最大金额
        trace("========================开始处理结束订单8-3-34-3 扣款金额=============================={$deduction_fee}");
        //保存已扣款的金额
        $deposit->deduction_fee = $deduction_fee;
        $deposit->save();
        trace('========================开始处理结束订单8-3-34-4 完成扣款金额的保存==============================');
        trace('========================开始处理结束订单8-3-34-5 开始调用退款接口==============================押金支付记录id：' . $deposit->id);
        //调用退款接口
        self::depositRefund($deposit->id);

        return $deduction_fee;
    }

    /**
     * 押金微信退款
     * @param int $deposit_id 押金支付记录id
     */
    public static function wechatRefund($deposit_id){
        trace('========================开始处理结束订单8-3-34-5-7-1 开始执行线上退款==============================' . $deposit_id);
        $deposit = LeaseDeposit::where(['id' => $deposit_id,'deletetime' => null])->find();
        trace('========================开始处理结束订单8-3-34-5-7-2 押金支付记录==============================' . json_encode($deposit));
        if(!$deposit){

            throw new Exception('押金充值记录不存在');
            return false;
        }
        if($deposit['status'] != self::STATUS_TUIKUANGZHONG){
            throw new Exception('押金非退款中状态');
            return false;
        }
        if($deposit['refund_fee'] <= 0){
            throw new Exception('退款金额不得小于0');
            return false;
        }
        trace('========================开始处理结束订单8-3-34-5-7-3 查询支付记录==============================' . $deposit->id);
        $pay = Pay::where(['lease_deposit_id' => $deposit->id,'deletetime' => null,'status' => Pay::STATUS_YIZHIFU])->order('id desc')->find();
        trace('========================开始处理结束订单8-3-34-5-7-4 支付记录==============================' . json_encode($pay));
        if(!$pay){
            throw new Exception('支付记录不存在');
            return false;
        }
        if($pay['refund_type'] == Pay::REFUND_TYPE_TUIKUANZHONG){
            throw new Exception('退款中，请勿重复操作');
            return false;
        }

        if($pay['refund_type'] == Pay::REFUND_TYPE_YITUIKUAN){
            throw new Exception('已退款，请勿重复操作');
            return false;
        }
        if($pay->pay_type == Pay::PAY_TYPE_WECHAT){//支付类型 = 微信支付
            trace('========================开始处理结束订单8-3-34-5-7-5 微信支付退款==============================');
            //读取配置文件
            $config = Config::get('wechatandalipay.wechat_miniapp');
            $Host = 'https://xcx.xiazhaotaiqiu.com/';//Config::get('site.Host');
            $wxappid = $config['appid'];
            $mch_id = $config['mch_id'];
            $notify_url = $Host . $config['wechatRefundNotify'];
            $wxkey = $config['wxkey_v2'];
            $apiclient_cert = ROOT_PATH . $config['apiclient_cert'];
            $apiclient_key = ROOT_PATH . $config['apiclient_key'];
            $wechatAppPay = new wechatapppay($wxappid, $mch_id, $notify_url, $wxkey, $apiclient_cert, $apiclient_key);
            trace('========================开始处理结束订单8-3-34-5-7-6 微信支付退款==============================');
            $sn = $pay['ordersn'];
            $transaction_id = $pay['transaction_id'];
            trace('========================开始处理结束订单8-3-34-5-7-7 微信支付退款==============================');
            $wx_orderQuery = $wechatAppPay->orderQuery($sn);
            //退款
            $params = array();
            $params['out_trade_no'] = $sn;
            $params['out_refund_no'] = Pay::requestNo();
            $params['refund'] = $deposit['refund_fee'] * 100;
            $params['total'] =$deposit['amount'] * 100;
            $params['currency'] = 'cny';
            //$params['total_fee'] = $money;       //必填项 订单金额 单位为分所以要*100
            $params['return_oid'] = $transaction_id;
            $params['notify_url'] = $notify_url; //退款单号
            trace('========================开始处理结束订单8-3-34-5-7-8 微信支付退款==============================');
            $wx_result = $wechatAppPay->refund($params);
            trace('========================开始处理结束订单8-3-34-5-7-9 微信支付退款结果==============================' . json_encode($wx_result));
            if ($wx_result['return_code'] == 'SUCCESS') {
                if ($wx_result['result_code'] == 'SUCCESS') {
                    $pay->return_fee = $deposit['refund_fee'];//退款金额
                    $pay->refund_desc = '租赁订单押金退款';//退款备注
                    $pay->refund_type = Pay::REFUND_TYPE_TUIKUANZHONG;//退款状态
                    $pay->refund_time = time();//发起退款时间
                    $pay->save();
                } else {
                    throw new Exception($wx_result['return_msg']);
                    return false;
                }
            } else {
                throw new Exception('通信失败，错误原因：' . $wx_result['err_code_des']);
                return false;
            }
        }
        else if($pay->pay_type == Pay::PAY_TYPE_ALIPAY) {//支付类型 = 支付宝支付
            $refund_sn = Pay::createPayOrderSn();
            Pay::submitRefund(
                $pay->payment_amount,
                $deposit['refund_fee'],
                $pay->ordersn,
                $refund_sn,
                'alipay',
                '台球柜租赁预付金剩余退款'
            );
            $pay->return_fee = $deposit['refund_fee'];//退款金额
            $pay->refund_desc = '租赁订单押金退款';//退款备注
            $pay->refund_type = Pay::REFUND_TYPE_TUIKUANZHONG;//退款状态
            $pay->refund_time = time();//发起退款时间
            $pay->save();
        }

    }


    //支付完成时间
    public function getPaymentTimeAttr($value){
        return $value != null ? date('Y-m-d H:i:s', $value) : '';
    }

    //退款完成时间
    public function getRefundCompleteTimeAttr($value){
        return $value != null ? date('Y-m-d H:i:s', $value) : '';
    }


    public function getStatusList()
    {
        return ['-1' => __('已取消'), '1' => __('未支付'), '2' => __('已支付'), '3' => __('已退款')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }



}
